//
//  ViewController.m
//  OCCallJS&&JSCallOC
//
//  Created by tanchao on 15/11/23.
//  Copyright © 2015年 谈超. All rights reserved.
//

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
@interface ViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIButton *ocButton;
@property (nonatomic, assign,getter=isHidden) BOOL hidden;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.ocButton];
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"test" ofType:@"html"]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"tanchaolog"] = ^() {
        NSArray *args = [JSContext currentArguments];
        for (JSValue *jsVal in args) {
            self.hidden = ![jsVal toBool];
        }
    };
    
}
- (void)setHidden:(BOOL)hidden{
    _hidden = hidden;
    NSString *title = [NSString stringWithFormat:@"%@",(_hidden)?@"显示":@"隐藏"];
    [self.ocButton setTitle:title forState:UIControlStateNormal];
    self.ocButton.backgroundColor = (_hidden)? [UIColor redColor]:[UIColor blueColor];
}
- (void)buttonClick{
    self.hidden = !self.isHidden;
    NSString *js = [NSString stringWithFormat:@"tt('%d');",self.isHidden];
    [self.webView stringByEvaluatingJavaScriptFromString:js];
    NSLog(@"%@",(self.isHidden)?@"隐藏":@"显示");
}
- (UIWebView *)webView{
    if (_webView == nil) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height - 80)];
        _webView.delegate=self;
        _webView.backgroundColor = [UIColor blueColor];
        _webView.scalesPageToFit = YES;
    }
    return _webView;
}
- (UIButton *)ocButton{
    if (_ocButton == nil) {
        _ocButton = [[UIButton alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.webView.frame), [UIScreen mainScreen].bounds.size.width, 60)];
        _ocButton.backgroundColor = [UIColor blueColor];
        [_ocButton setTitle:@"隐藏" forState:UIControlStateNormal];
        _ocButton.tag = 20;
        [_ocButton addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _ocButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
